import { GAME_CONFIG } from './config.js';

export class ObstacleSystem {
    constructor(scene) {
        this.scene = scene;
        this.cones = [];
        this.speed = GAME_CONFIG.OBSTACLE_CONFIG.BASE_SPEED;
        this.frequency = 1; // 障碍物生成频率的基准值
        this.currentObstacleType = 0; // 当前关卡的障碍物类型
        this.initialize();
    }

    initialize() {
        const { count, spacing, positions, height } = GAME_CONFIG.OBSTACLE_CONFIG;
        
        // 加载SVG贴图
        const textureLoader = new THREE.TextureLoader();
        const textures = {
            spike: textureLoader.load('assets/images/obstacle_spike.svg'),
            cube: textureLoader.load('assets/images/obstacle_cube.svg'),
            crystal: textureLoader.load('assets/images/obstacle_crystal.svg'),
            ring: textureLoader.load('assets/images/obstacle_ring.svg')
        };
        
        for (let i = 0; i < count; i++) {
            // 使用当前关卡的障碍物类型
            const obstacleType = this.currentObstacleType;
            
            // 创建平面几何体
            const geometry = new THREE.PlaneGeometry(6, 6);
            
            // 根据类型选择贴图
            const texture = obstacleType === 0 ? textures.spike :
                          obstacleType === 1 ? textures.cube :
                          obstacleType === 2 ? textures.crystal :
                          textures.ring;
            
            // 创建材质
            const material = new THREE.SpriteMaterial({
                map: texture,
                transparent: true,
                opacity: obstacleType === 0 ? 1 : 0.9
            });
            
            // 创建精灵
            const obstacle = new THREE.Sprite(material);
            obstacle.scale.set(6, 6, 1);
            
            // 设置障碍物位置
            obstacle.position.z = -i * spacing - spacing;
            obstacle.originalZ = obstacle.position.z;
            obstacle.type = obstacleType;
            obstacle.h = obstacleType === 0 ? (Math.random() <= 0.33 ? height.MAX : height.MIN) : 4;
            
            // 为不同类型的障碍物设置不同的动画参数
            obstacle.rotationSpeed = {
                x: (Math.random() - 0.5) * 0.02,
                y: (Math.random() - 0.5) * 0.02,
                z: (Math.random() - 0.5) * 0.02
            };
            
            // 随机决定障碍物的X坐标位置（左、中、右）
            const dirR = Math.random();
            if (dirR <= 0.33) {
                obstacle.position.x = positions.LEFT;
            } else if (dirR >= 0.66) {
                obstacle.position.x = positions.RIGHT;
            } else {
                obstacle.position.x = positions.CENTER;
            }

            // 50%概率将障碍物放在天花板上
            if (Math.random() <= 0.5) {
                obstacle.position.y = 15;
                // 对于尖刺型，翻转180度
                if (obstacleType === 0) {
                    obstacle.rotation.z = Math.PI;
                }
            } else {
                obstacle.position.y = 0;
            }

            // 保存初始状态
            obstacle.initialY = obstacle.position.y;
            obstacle.initialRotationZ = obstacle.rotation.z || 0;
            
            this.cones.push(obstacle);
            this.scene.add(obstacle);
        }
    }

    update(panSpeed) {
        const adjustedSpeed = panSpeed * this.speed;
        
        for (const obstacle of this.cones) {
            // 更新障碍物位置
            obstacle.position.z += adjustedSpeed;
            
            // 根据障碍物类型应用不同的动画效果
            switch(obstacle.type) {
                case 1: // 旋转立方体
                    obstacle.rotation.x += obstacle.rotationSpeed.x;
                    obstacle.rotation.y += obstacle.rotationSpeed.y;
                    break;
                    
                case 2: // 菱形水晶
                    obstacle.rotation.y += obstacle.rotationSpeed.y * 2;
                    break;
                    
                case 3: // 圆环
                    obstacle.rotation.x += obstacle.rotationSpeed.x;
                    obstacle.rotation.z += obstacle.rotationSpeed.z;
                    break;
            }
            
            // 如果障碍物移动到了玩家后方，将其重置到更远的前方
            if (obstacle.position.z > 50) {
                // 找到最远的障碍物的z坐标
                const farthestZ = Math.min(...this.cones.map(c => c.position.z));
                // 根据频率调整间距
                const spacing = GAME_CONFIG.OBSTACLE_CONFIG.spacing / this.frequency;
                // 将当前障碍物放置到最远处再往后一个间距
                obstacle.position.z = farthestZ - spacing;
                
                // 随机决定新的X坐标位置（左、中、右）
                const dirR = Math.random();
                const { LEFT, CENTER, RIGHT } = GAME_CONFIG.OBSTACLE_CONFIG.positions;
                
                if (dirR <= 0.33) {
                    obstacle.position.x = LEFT;
                } else if (dirR >= 0.66) {
                    obstacle.position.x = RIGHT;
                } else {
                    obstacle.position.x = CENTER;
                }
                
                // 恢复初始的Y位置和旋转
                obstacle.position.y = obstacle.initialY;
                obstacle.rotation.z = obstacle.initialRotationZ;
            }
        }
    }

    // 更新障碍物移动速度
    updateSpeed(newSpeed) {
        this.speed = newSpeed;
    }

    // 更新障碍物生成频率
    updateFrequency(newFrequency) {
        this.frequency = newFrequency;
    }

    checkCollision(player, hasShield) {
        for (const obstacle of this.cones) {
            const dist = player.pos.distanceTo(obstacle.position);
            let collisionSize;
            
            // 根据障碍物类型设置不同的碰撞范围
            switch(obstacle.type) {
                case 0: // 尖刺型
                    collisionSize = obstacle.h > GAME_CONFIG.OBSTACLE_CONFIG.height.MIN ? 5 : 3;
                    break;
                case 1: // 旋转立方体
                    collisionSize = 3;
                    break;
                case 2: // 菱形水晶
                    collisionSize = 3.5;
                    break;
                case 3: // 圆环
                    collisionSize = 4;
                    break;
                default:
                    collisionSize = 3;
            }
            
            if (Math.floor(dist) < collisionSize && !player.hit && !hasShield) {
                return true;
            }
        }
        return false;
    }

    // 更新障碍物类型但保持位置不变
    setObstacleType(type) {
        this.currentObstacleType = type;
        
        // 加载新类型的贴图
        const textureLoader = new THREE.TextureLoader();
        const texture = type === 0 ? textureLoader.load('assets/images/obstacle_spike.svg') :
                       type === 1 ? textureLoader.load('assets/images/obstacle_cube.svg') :
                       type === 2 ? textureLoader.load('assets/images/obstacle_crystal.svg') :
                                  textureLoader.load('assets/images/obstacle_ring.svg');

        // 更新所有现有障碍物的外观
        for (const obstacle of this.cones) {
            // 保存原始位置和状态
            const originalPosition = obstacle.position.clone();
            const originalY = obstacle.initialY;
            const originalRotationZ = obstacle.initialRotationZ;

            // 更新类型和贴图
            obstacle.type = type;
            obstacle.material.map = texture;
            obstacle.material.needsUpdate = true;

            // 恢复原始位置和状态
            obstacle.position.copy(originalPosition);
            obstacle.initialY = originalY;
            obstacle.initialRotationZ = originalRotationZ;
            obstacle.position.y = originalY;
            obstacle.rotation.z = originalRotationZ;

            // 更新动画参数
            if (type === 0) { // 尖刺型
                obstacle.rotationSpeed = { x: 0, y: 0, z: 0 };
            } else {
                obstacle.rotationSpeed = {
                    x: (Math.random() - 0.5) * 0.02,
                    y: (Math.random() - 0.5) * 0.02,
                    z: (Math.random() - 0.5) * 0.02
                };
            }
        }
    }

    reset() {
        // 移除所有现有的障碍物
        for (const obstacle of this.cones) {
            this.scene.remove(obstacle);
        }
        this.cones = [];
        
        // 重新初始化障碍物
        this.initialize();
        
        this.speed = GAME_CONFIG.OBSTACLE_CONFIG.BASE_SPEED;
        this.frequency = 1;
    }
}